import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { visitorSheetApi } from '@/api'
import type {
  VisitorSheet,
  VisitorSheetWithDetails,
  VisitorSheetCreate,
  VisitorSheetUpdate,
} from '@/api/types'
import notify from '@/utils/notify'

/**
 * 访客单 Store
 * Setup Store 风格
 */
export const useVisitorSheetStore = defineStore('visitorSheet', () => {
  // ========== State ==========
  const visitorSheets = ref<VisitorSheet[]>([])
  const currentVisitorSheet = ref<VisitorSheetWithDetails | null>(null)
  const total = ref(0)
  const loading = ref(false)

  // ========== Getters ==========
  const highIntentionSheets = computed(() =>
    visitorSheets.value.filter((vs: VisitorSheet) => vs.intention === 'high')
  )

  const recentSheets = computed(
    () => visitorSheets.value.slice(0, 10) // 最近10条
  )

  const averageSatisfaction = computed<number>(() => {
    const sheets = visitorSheets.value.filter((vs: VisitorSheet) => vs.satisfaction != null)
    if (sheets.length === 0) return 0
    const sum = sheets.reduce((acc: number, vs: VisitorSheet) => acc + (vs.satisfaction || 0), 0)
    return Number((sum / sheets.length).toFixed(1))
  })

  // ========== Actions ==========

  /**
   * 获取访客单列表
   */
  async function fetchVisitorSheets(
    params: {
      page: number
      page_size: number
      lead_id?: number
      property_id?: number
      agent_id?: number
      start_date?: string
      end_date?: string
      intention?: string
    } = { page: 1, page_size: 10 }
  ) {
    loading.value = true
    try {
      const res = await visitorSheetApi.getList(params)
      visitorSheets.value = res.items
      total.value = res.total
      return res
    } catch (error) {
      console.error('获取访客单列表失败', error)
      notify.error('获取访客单列表失败')
      return null
    } finally {
      loading.value = false
    }
  }

  /**
   * 获取访客单详情
   */
  async function fetchVisitorSheet(id: number) {
    loading.value = true
    try {
      const res = await visitorSheetApi.getById(id)
      currentVisitorSheet.value = res
      return res
    } catch (error) {
      console.error('获取访客单详情失败', error)
      notify.error('获取访客单详情失败')
      return null
    } finally {
      loading.value = false
    }
  }

  /**
   * 创建访客单
   */
  async function createVisitorSheet(data: VisitorSheetCreate) {
    loading.value = true
    try {
      const res = await visitorSheetApi.create(data)
      notify.success('创建访客单成功')
      return res
    } catch (error) {
      console.error('创建访客单失败', error)
      notify.error('创建访客单失败')
      return null
    } finally {
      loading.value = false
    }
  }

  /**
   * 更新访客单
   */
  async function updateVisitorSheet(id: number, data: VisitorSheetUpdate) {
    loading.value = true
    try {
      const res = await visitorSheetApi.update(id, data)
      notify.success('更新访客单成功')
      return res
    } catch (error) {
      console.error('更新访客单失败', error)
      notify.error('更新访客单失败')
      return null
    } finally {
      loading.value = false
    }
  }

  /**
   * 删除访客单
   */
  async function deleteVisitorSheet(id: number) {
    loading.value = true
    try {
      const res = await visitorSheetApi.delete(id)
      notify.success('删除访客单成功')
      return res
    } catch (error) {
      console.error('删除访客单失败', error)
      notify.error('删除访客单失败')
      return null
    } finally {
      loading.value = false
    }
  }

  /**
   * 批量删除访客单
   */
  async function deleteVisitorSheets(ids: number[]) {
    loading.value = true
    try {
      // 注意：API中可能没有批量删除方法，需要单独实现
      const promises = ids.map(id => visitorSheetApi.delete(id))
      const res = await Promise.all(promises)
      notify.success('批量删除访客单成功')
      return res
    } catch (error) {
      console.error('批量删除访客单失败', error)
      notify.error('批量删除访客单失败')
      return null
    } finally {
      loading.value = false
    }
  }

  return {
    // State
    visitorSheets,
    currentVisitorSheet,
    total,
    loading,

    // Getters
    highIntentionSheets,
    recentSheets,
    averageSatisfaction,

    // Actions
    fetchVisitorSheets,
    fetchVisitorSheet,
    createVisitorSheet,
    updateVisitorSheet,
    deleteVisitorSheet,
    deleteVisitorSheets,
  }
})
